package com.cheng.week07.db1_0;

import java.sql.*;

/**
 * @author yangcheng(darren)
 * @date 2021/08/09
 * @copyright 2021 Bizfocus All Rights Reserved
 * @description 数据库连接工具
 */
public class DBUtil {

    private static final String QUERYURL = "jdbc:mysql://127.0.0.1:3306/TEST?useUnicode=true&amp;characterEncoding=utf-8";
    private static final String UPDATEURL = "jdbc:mysql://127.0.0.1:3316/TEST?useUnicode=true&amp;characterEncoding=utf-8";
    private static final String USER = "root";
    private static final String PASSWORD = "tiger";

    private static Connection queryConn = null;

    private static Connection updateConn = null;

    static {
        getQueryConnection();
        getUpdateConnection();
    }

    public static void getQueryConnection() {
        try {
            //1.加载驱动程序
            Class.forName("com.mysql.jdbc.Driver");
            //2.获得数据库的连接
            queryConn = DriverManager.getConnection(QUERYURL, USER, PASSWORD);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }


    public static ResultSet querySql(String sql) throws SQLException {
        ResultSet rs = null;
        PreparedStatement pst = null;
        try {
            pst = queryConn.prepareStatement(sql);
            pst.setString(1, "xiao");
            pst.setString(2, "123");
            rs = pst.executeQuery();
            return rs;
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        } finally {
            //处理数据库的返回结果(使用ResultSet类)
            //关闭资源
            if (null != rs) {
                rs.close();
            }
            if (null != pst) {
                pst.close();
            }
        }
    }

    public static void getUpdateConnection() {
        try {
            //1.加载驱动程序
            Class.forName("com.mysql.jdbc.Driver");
            //2.获得数据库的连接
            updateConn = DriverManager.getConnection(UPDATEURL, USER, PASSWORD);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static ResultSet updateSql(String sql) throws SQLException {
        ResultSet rs = null;
        PreparedStatement pst = null;
        try {
            pst = updateConn.prepareStatement(sql);
            pst.setString(1, "xiao");
            pst.setString(2, "123");
            rs = pst.executeQuery();
            return rs;
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        } finally {
            //处理数据库的返回结果(使用ResultSet类)
            //关闭资源
            if (null != rs) {
                rs.close();
            }
            if (null != pst) {
                pst.close();
            }
        }
    }
}
